<template>
  <a-modal
    :visible="visible"
    width="900px"
    :afterClose="hanldeAfterClose"
    @cancel="close"
    @ok="handleSubmit"
    okText="导入"
    :confirmLoading="isSubmiting"
    title="批量导入"
  >
    <a-upload
      name="file"
      rowKey="uid"
      accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
      :multiple="true"
      :action="action"
      :file-list="fileList"
      :headers="headers"
      :showUploadList="false"
      :before-upload="beforeUpload"
      @change="handleChange"
    >
      <div class="text-right m-b-24" style="width: 852px">
        <y-button icon="upload" type="primary">点击上传</y-button>
      </div>
    </a-upload>
    <a-table :columns="columns" :dataSource="fileList"></a-table>
  </a-modal>
</template>

<script>
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { importPackExcel } from '@/api/followUpManagement'
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      isSubmiting: false,
      columns: [
        {
          title: '文件名',
          dataIndex: 'name',
          align: 'center'
        },
        {
          title: '文件大小',
          dataIndex: 'size',
          align: 'center',
          customRender: (text) => this.bytesToSize(text)
        },
        {
          title: '状态',
          dataIndex: 'status',
          align: 'center',
          customRender: (text) => {
            const textStatus = new Map([
              ['done', '上传成功'],
              ['error', '上传失败'],
              ['uploading', '上传中'],
              ['removed', '已删除'],
              ['wait', '未上传']
            ])
            const colorStatus = new Map([
              ['done', 'text-success'],
              ['error', 'text-error'],
              ['uploading', 'text-primary'],
              ['removed', 'text-warning'],
              ['wait', 'text-info']
            ])
            return <span class={colorStatus.get(text || 'wait')}>{textStatus.get(text || 'wait')}</span>
          }
        },
        {
          title: '操作',
          align: 'center',
          customRender: (text, record) => (
            <y-button
              type="link"
              class="text-error"
              onclick={() => {
                this.handleDelete(record)
              }}
            >
              删除
            </y-button>
          )
        }
      ],
      fileList: [],
      action: process.env.VUE_APP_API_BASE_URL + '/api/uploadpictures/UploadPicturesEXCEL',
      headers: {
        Authorization: storage.get(ACCESS_TOKEN),
        GF: this.$store.getters.userid
      }
    }
  },
  methods: {
    bytesToSize (bytes) {
      if (bytes === 0) return '0 B'
      var k = 1024
      var sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
      var i = Math.floor(Math.log(bytes) / Math.log(k))

      return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i]
    },
    beforeUpload (file) {
      const fileType = file.name.split('.').pop()
      if (['xls', 'xlsx'].indexOf(fileType.toLowerCase()) === -1) {
        this.$message.warning('只能上传.XLS.XLSX格式的文件!')
        return false
      }
      return true
    },
    handleDelete (file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },
    handleChange (info) {
      const fileType = info.file.name.split('.').pop()
      if (['xls', 'xlsx'].indexOf(fileType.toLowerCase()) === -1) {
        return
      }
      let fileList = [...info.fileList]
      fileList = fileList.map((file) => {
        if (file.response) {
          file.url = file.response.data[0]
        }
        return file
      })

      this.fileList = fileList
    },
    close () {
      this.$emit('update:visible', false)
      this.fileList = []
    },
    handleSubmit () {
      if (this.$isEmpty(this.fileList)) {
        this.$message.warning('请上传文件')
        return
      }
      let isError = false
      let uploadIndex = 0
      this.isSubmiting = true
      const urls = this.fileList.map((e) => e.url)
      const uploadImport = () => {
        if (isError) {
          this.isSubmiting = false
          this.$message.error('导入失败')
          return
        }
        if (uploadIndex === urls.length) {
          this.$message.success('全部导入成功')
          this.isSubmiting = false
          this.close()
          return
        }
        importPackExcel({
          fileexcel: urls[uploadIndex]
        })
          .then((res) => {
            uploadIndex++
            uploadImport()
            this.handleDelete(this.fileList[uploadIndex])
          })
          .catch(() => {
            isError = true
            uploadImport()
          })
      }
      uploadImport()
    },
    hanldeAfterClose () {}
  }
}
</script>
<style lang="less" scoped>
</style>
